package logger

import (
	"errors"
)

var (
	// ErrChannelFull ...
	ErrChannelFull = errors.New("日志通道缓存已满，请取出数据")
)

type logChannelWriter struct {
	ch chan []byte
}

// NewChannelWriter ...
func NewChannelWriter(ChannelLen int) *logChannelWriter {
	if !(ChannelLen > 0) {
		return &logChannelWriter{ch: make(chan []byte)}
	} else {
		return &logChannelWriter{ch: make(chan []byte, ChannelLen)}
	}
}

// Write ...
func (l logChannelWriter) Write(p []byte) (n int, err error) {
	data := make([]byte, len(p), len(p))
	copy(data, p)
	select {
	case l.ch <- data:
		return len(data), nil
	default:
		return 0, ErrChannelFull
	}
}

// Close ...
func (l logChannelWriter) Close() error {
	close(l.ch)
	return nil
}
